 <?php

require_once('../../includes/classes/core.php');
mysql_query("SET NAMES 'utf8'");
$action 	= $_REQUEST['act'];
$error		= '';
$data		= '';

switch ($action) {
    case 'checker':
        $data = array(
        'chat' => array()
        );
        mysql_query("SET @i = 0;");
        $checker = mysql_query("SELECT 	chat.`id`,
                        				chat.`ip`,
                        				chat.`name`,
                                        'cers' AS `order`,
                                        SEC_TO_TIME((NOW() - chat.`start_date`)) AS `date`,
                                        users.`ext`,
                                        chat.`user_id`,
                                        @i := @i + 1 AS `num`,
                                        IF(@i = 1, '', IF(@i = 2, '#E64A45', IF(@i = 3, '#257E78', IF(@i = 4, '#29264E', IF(@i = 5, '#00904B',''))))) AS `color`
                                FROM 	`chat`
                                JOIN users ON chat.user_id = users.id
                                WHERE 	chat.`status`   = 0
                                AND 	chat.`actived`  = 1;");

        mysql_query("SET @r = 0;");
        $checker1 = mysql_query("   SELECT 	`id`,
                            				`ip`,
                            				`name`,
                                            @r := @r + 1 AS `order`,
                                            SEC_TO_TIME((NOW() - `start_date`)) AS `date`,
                                            `user_id`
                                    FROM 	`chat`
                                    WHERE 	`status`   = 0
                                    AND 	`actived`  = 1;");

        $station = '<h2>სთეიშენები</h2>
                      <table id="all_chat">
                      <tr>
                        <th style="display:none;"></th>
                        <th>სთეიშენი</th>
                        <th>სტატუსი</th>
                        <th>დრო</th>
                        <th>აბონენტი</th>
                        <th>IP</th>
                      </tr>
                      <tr>
                    ';

        $queu = '
            <h2>რიგი</h2>
                      <table id="all_chat">
                      <tr>
                        <th style="display:none;"></th>
                        <th>IP</th>
                        <th>აბონენტი</th>
                        <th>პოზიცია</th>
                        <th>ლოდინი დრო</th>
                      </tr>
                      ';

        $i = 0;
        while ($checker_row = mysql_fetch_assoc($checker)){

            if($checker_row[user_id] != ''){
                $station1 .= '
                      <tr id="station">
                        <td style="display:none;">'.$checker_row[id].'</td>
                        <td>'.$checker_row[ext].'</td>
                        <td>'.$checker_row[order].'</td>
                        <td>'.$checker_row[date].'</td>
                        <td id="station_name" style="cursor: pointer;" onclick="opendialog('.$checker_row[num].',\''.$checker_row[color].'\',\''.$checker_row[name].'\')">'.$checker_row[name].'</td>
                        <td>'.$checker_row[ip].'</td>
                      </tr>
                      ';
            }

        }

        while ($checker_row1 = mysql_fetch_assoc($checker1)){

            if($checker_row1[user_id] == ''){
                $queu1 .= '
                      <tr id="queue">
                        <td style="display:none;">'.$checker_row1[id].'</td>
                        <td>'.$checker_row1[ip].'</td>
                        <td>'.$checker_row1[name].'</td>
                        <td>'.$checker_row1[order].'</td>
                        <td>'.$checker_row1[date].'</td>
                      </tr>
                      ';
            }

        }

        $station .= $station1;
        $station .= '</table>';

        $queu .= $queu1;
        $queu .= '</table>';

        if($station1 != ''){
            $data[chat][] = $station;
        }
        if($queu1 != ''){
            $data[chat][] = $queu;
        }
        break;
    case 'message' :
        $chat_id = mysql_real_escape_string($_REQUEST['id']);
         
        $data = array(
            'message' => array()
        );

        $message = mysql_query("SELECT      IF(`chat_detail`.`type` = 1, `chat`.`name`, CONCAT('<span style=\"color: #7DB542;\">',`users`.`username`,'</span>')) AS `name`,
            `chat_detail`.`message`,
            IF(`chat_detail`.`type` = 1, CONCAT('[',DATE_FORMAT(`chat_detail`.`date`, '%H:%i:%s'),']'), CONCAT('<span style=\"color: #7DB542;\">[',DATE_FORMAT(`chat_detail`.`date`, '%H:%i:%s'),']</span>')) AS `date`
            FROM        `chat_detail`
            JOIN        `chat` ON `chat_detail`.`chat_id` = `chat`.`id`
            LEFT JOIN   `users` ON `chat`.`user_id` = `users`.`id`
            WHERE       `chat`.`id` = $chat_id
            AND         `status`   = 1
            ORDER BY    `chat_detail`.`date` ASC;");

            $chhc = mysql_num_rows($message);

        while ($message_row = mysql_fetch_assoc($message)){

        $data[message][] = '
        <span id="chat_body_process">
            <span style="font-weight: bold;">'.$message_row[name].'</span>
                        <span style="margin-left:6px; font-weight: bold;">'.$message_row[date].':</span>
                        <span style="margin-left:6px;">'.mysql_real_escape_string($message_row[message]).'</span>
                        </span>
                            ';

        }

		break;
            case 'guest_chat':
                $id_add = mysql_real_escape_string($_REQUEST['id_add_guest']);
                $text_add = mysql_real_escape_string($_REQUEST['text_add_guest']);
                $num_row = cheker($id_add);
                 
                if(!empty($id_add) and !empty($text_add)  and $num_row > 0){
                mysql_query("INSERT INTO `chat_detail` (`chat_id`, `date`, `message`, `type`) VALUES ('$id_add', NOW(), '$text_add', '1');");
}
break;
case 'close_chat':
$close_id = mysql_real_escape_string($_REQUEST['close_id']);
 
if(!empty($close_id)){
    mysql_query("UPDATE `chat` SET `status`='1', `end_date`=NOW() WHERE (`id`='$close_id');");
    unset($_SESSION['chat_session_id']);
}
break;

case 'select_chat':
$up_id = mysql_real_escape_string($_REQUEST['up_id']);
$user  = $_SESSION['USERID'];
$cheker_user = cheker_user($up_id);
 
if(!empty($up_id) and $cheker_user > 0){
    mysql_query("UPDATE `chat` SET `user_id`='$user' WHERE (`id`='$up_id');");
}
break;
case 'check_session':
if(time() - $_SESSION['GUEST_TIME'] > 20){
session_unset($_SESSION['GUEST_TIME']);
}
break;
case 'get_list' :
		    $count = 		$_REQUEST['count'];
		    $hidden = 		$_REQUEST['hidden'];
		    $start = 		$_REQUEST['start'];
		    $end  = 		$_REQUEST['end'];
		    
		    $rResult = mysql_query("SELECT 	chat.id,
                            				chat.id,
                            				chat.start_date,
                            				chat.end_date,
                            				chat.`name`,
                            				chat.email,
                            				chat.ip,
                            				persons.`name`
                                    FROM    chat
                                    LEFT JOIN users ON chat.user_id = users.id
                                    LEFT JOIN persons ON users.person_id = persons.id
                                    WHERE chat.actived = 1 AND DATE(chat.start_date) >= '$start' AND DATE(chat.start_date) <= '$end' AND chat.status = 1");
		  
		    $data = array(
		        "aaData"	=> array()
		    );

		    while ( $aRow = mysql_fetch_array( $rResult ) )
		    {
		        $row = array();
		        for ( $i = 0 ; $i < $count ; $i++ )
		        {
		            /* General output */
		            $row[] = $aRow[$i];
		        }
		        $data['aaData'][] = $row;
		    }

		break;
	default:
		$error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Request Functions
* ******************************
*/

function cheker($chat_id){
    $checker = mysql_num_rows(mysql_query(" SELECT 	`id`
                                            FROM 	`chat`
		            WHERE 	`status`   = 0
		        AND 	`actived`  = 1
		            AND     `id` = '$chat_id';"));
		            return $checker;
}

function cheker_user($chat_id){
$cheker_user = mysql_num_rows(mysql_query(" SELECT 	`user_id`
    FROM 	`chat`
    WHERE 	`status`   = 0
    AND 	`actived`  = 1
    AND     `id` = '$chat_id'
    AND     ISNULL(`user_id`);"));
    return $cheker_user;
		        }


?>